import store from '@/store' 
import { getToken } from '@/utils/auth'

const isEnable = process.env.VUE_APP_SSO_ENABLE === 'YES'
const hasPrefix = process.env.VUE_APP_SSO_PREFIX !== undefined
/**
* 单点登录
*/
const init = (callback) => {
    if (!isEnable) { 
        console.log('--未启用单点登录, 请设置SSO_ENABLE 为YES')
        return Promise.resolve({
            success: false,
            error: 'not enable sso'
        })
    }
    if (!hasPrefix) {
        console.log('--- 缺少cas配置 --')
        return Promise.reject({
            success: false,
            error: '缺少cas地址配置'
        })
    }
    console.log("-------单点登录开始-------");
    // 从 Cookie 中获取token
    let token = getToken()
    // 从Url中获取ST
    let {ticket: st} = getUrlParams();
    // 获取当前 Service 地址
    let sevice = getServiceUrl()
    console.log(token)
    if (token) {
        // 若 token 存在，则认为登录成功
        return loginSuccess(callback);
    } else {
        // 若 token 不存在，则根据 ST 进行下一步判断 
        console.log(st)
        if (st) {
            // 校验 ST 是否有效
            return validateSt(st, sevice, callback);
        }
        else {
            // 重定向到 CAS Server
            redirectToCasServer()
        }
    }
    console.log("-------单点登录结束-------");
};
const SSO = {
    init: init,
    enable: isEnable,
    redirectToLogout: () => window.location.href = getCasServer('logout'),
};
function getUrlParams() {
    let url = document.location.toString(); let arrObj = url.split("?");
    if (arrObj.length > 1) {
        let result = {}
        let arrPara = arrObj[1].split("&"); let arr;
        for (let i = 0; i < arrPara.length; i++) {
            let [ key,value] = arrPara[i].split("=");
            result[key] = value
        }
        return result;
    }
    else {
        return {};
    }
}
function getFilteredQueryString() {
    let filterKey = ['ticket']
    let params = getUrlParams()
    let result = []
    for(let key in params) {
        if (!filterKey.includes(key)) result.push(`${key}=${params[key]}`)
    }
    console.log(result)
    return result.join('&')
}
// 后端自定义的校验 ST 接口
function validateSt(ticket, service, callback) {
    let params = {
        ticket: ticket,
        service: service
    };
    
    return store.dispatch('LoginSSO', params).then(res => {
        if (res.success) {
            return loginSuccess()
        } else {
            redirectToCasServer()
        }
    }).catch((error) => {
        console.log(error);
        return {
            success: false,
            error
        }
    });
}
function loginSuccess(callback) {
    return Promise.resolve({
        success: true
    })
}
function getServiceUrl (type) {
    if (type === 'logout') {
        return window.location.origin + '/yzq_manage/'
    }
    let service = window.location.origin + window.location.pathname
    let queryString = getFilteredQueryString()
    if (queryString) {
        service += '?' + queryString
    }
    return service
}
function redirectToCasServer () {
    window.location.href =  getCasServer('login')
}
function getCasServer(type = 'login') {
    return `${process.env.VUE_APP_SSO_PREFIX}/${type}?service=${encodeURIComponent(getServiceUrl(type))}`
}
export default SSO;